<template>
    <div class="tradmark">
        <el-card>
            <el-button type="primary" icon="Plus" @click="addTradmark">添加品牌</el-button>
            <el-table style="width: 100%" border :data="tradmarkList">
                <el-table-column label="序号" type=index width="100" align="center" />
                <el-table-column prop="tmName" label="品牌名称" width="180" />
                <el-table-column label="品牌LOGO">
                    <template #default="scope">
                        <img :src="scope.row.logoUrl" alt="" style="width: 100px;height: 100px;">
                    </template>
                </el-table-column>
                <el-table-column prop=" address" label="品牌操作">
                    <template #default="scope">
                        <el-button icon="Edit" @click="updateTradmark(scope.row)">
                            编辑
                        </el-button>
                        <el-popconfirm width="180" :title="`你确定要删除${scope.row.tmName}吗？`"
                            @confirm="deleteTradmark(scope.row.id)">
                            <template #reference>
                                <el-button icon="Delete" type="danger">
                                    删除
                                </el-button>
                            </template>
                        </el-popconfirm>


                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[3, 5, 7]"
                layout=" prev, pager, next, jumper,->,total, sizes" :total="total">
            </el-pagination>

        </el-card>
        <el-dialog v-model="dialogVisible" :title="tradmarkform.id ? '修改品牌' : '添加品牌'" width="500"
            :before-close="handleClose">
            <el-form :model="tradmarkform" :rules="tradmarkRules" label-width="auto" style="width:80%"
                ref="ruleFormRef">
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input v-model="tradmarkform.tmName" autocomplete="on" placeholder="请您输入品牌名称" />
                </el-form-item>
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="true"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="tradmarkform.logoUrl" :src="tradmarkform.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirm">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue';
import { reqProductList, reqAddAndUpdateTradmark, reqDeleteTradmark } from '@/api/product/tradmark/index'
import type { records } from '@/api/product/tradmark/type'
import { ElMessage, type UploadProps } from 'element-plus'
import type { tradMark } from '@/api/product/tradmark/type'
import type { FormRules } from 'element-plus'
const currentPage = ref(1)
const pageSize = ref(3)
const total = ref()
const dialogVisible = ref(false)
const tradmarkList = ref<records>([])
const ruleFormRef = ref()
const tradmarkform = reactive<tradMark>({
    tmName: '',
    logoUrl: ''
})
const validatetmName = (rule: any, value: any, callback: any) => {
    let reg = /^[\u4e00-\u9fa5]{1,6}$/
    if (value == '') {
        callback(new Error('品牌名不能为空'))
    } else {
        if (reg.test(value)) {
            callback()
        } else {
            callback(new Error('品牌名为1-6位汉字'))
        }
    }
}
const validatelogoUrl = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请上传图片'))
    } else {
        callback()
    }
}
const tradmarkRules = reactive<FormRules<typeof tradmarkform>>({
    tmName: [{ validator: validatetmName, trigger: 'change' }],
    logoUrl: [{ validator: validatelogoUrl }]
})
const getTradMark = async () => {
    const res = await reqProductList(currentPage.value, pageSize.value)
    if (res.code == 200) {
        total.value = res.data.total
        tradmarkList.value = res.data.records
    }
}
onMounted(() => {
    getTradMark()

})
const handleSizeChange = () => {

    getTradMark()
}
const handleCurrentChange = () => {
    getTradMark()
}
const addTradmark = () => {
    dialogVisible.value = true
    Object.assign(tradmarkform, {
        tmName: '',
        logoUrl: '',
        id: ''
    })
    nextTick(() => {
        ruleFormRef.value.clearValidate('tmName')
        ruleFormRef.value.clearValidate('logoUrl')
    })
}
const updateTradmark = async (tradmark: any) => {
    Object.assign(tradmarkform, tradmark)
    dialogVisible.value = true
    nextTick(() => {
        ruleFormRef.value.clearValidate('tmName')
        ruleFormRef.value.clearValidate('logoUrl')
    })
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    tradmarkform.logoUrl = response.data
    ruleFormRef.value.clearValidate('logoUrl')
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg') {
        if (rawFile.size / 1024 / 1024 > 4) {
            ElMessage.error('图片大小应小于4MB')
            return false
        } else {
            return true
        }

    } else {
        ElMessage.error('图片格式不正确')
        return false
    }
}
const confirm = async () => {
    await ruleFormRef.value.validate()
    dialogVisible.value = false
    const res = await reqAddAndUpdateTradmark(tradmarkform)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: tradmarkform.id ? '修改成功' : '添加成功'
        })
        getTradMark()
    } else {
        ElMessage({
            type: 'error',
            message: tradmarkform.id ? '修改失败' : '添加失败'
        })
    }
}
const handleClose = () => {
    Object.assign(tradmarkform, {
        tmName: '',
        logoUrl: '',
        id: ''
    })
    dialogVisible.value = false


}
const deleteTradmark = async (id: number) => {
    const res = await reqDeleteTradmark(id)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
    getTradMark()
}
</script>

<style lang="scss" scoped>
.tradmark {
    margin-top: 15px;

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
}
</style>